import Vue from 'vue'
import axios from 'axios'
import { Message } from 'element-ui';
import router from '../router/index';
import store from '../store/index';
let qs=require('qs');
axios.defaults.timeout = 20000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = '';
axios.interceptors.request.use((req) => {
	let token='';
	if(store.getters.users){
		token=store.getters.users.token;
	}
	if(req.url.indexOf('login')==-1){
	 	req.url=req.url+'?token='+token;
	}
    if (req.method === 'post' && req.headers['Content-Type']!='multipart/form-data' ) {
     	req.data = JSON.stringify(req.data);
    }
    return req;
}, (error) =>{
	 return  Promise.reject(error)
});
axios.interceptors.response.use(function (response) {
	switch(response.data.code)
	{
			case '200':
			case 200:
			return response
			break;
			case '400' :
			case 400 :
			    Message.error(response.data.message);
				return Promise.reject(error);
			break;
	};
}, function (error) {
	if(error.toString()!='Cancel' && error.toString().indexOf('401')==-1){
		Message.error('系统错误');
	}
	if(error.toString().indexOf('401')!=-1){
		router.push('/login')
	}
	return Promise.reject(error)
})
axios.interceptors=(_this,data)=>{
	    switch(data.data.code)
	    {
	    	 case '200':
	    	 case 200:
	    	    return true;
	    	 break;
	    	 case '400' :
	    	  case 400 :
	    	     _this.$message.error(data.data.message);
			     return false;
	    	 break;
	    };
	    return true;
}
Vue.prototype.$http = axios;
Vue.prototype.$qs=qs;

